package tech.siso.frame;

import tech.siso.model.QmsCalculateParam;
import tech.siso.utils.StringUtil;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.InputStream;
import java.math.BigDecimal;

public class MainFrame extends Frame {
    public MainFrame() {
        super(
                String.format(
                        "扬声器Qms参数计算器 %s [by.青雨紫峰]",
                        //尝试读取当前程序版本号，jar包能读，开发的时候没有生成版本号文件，所以不显示
                        MainFrame.class.getPackage().getImplementationVersion() == null ? "" : "v" + MainFrame.class.getPackage().getImplementationVersion()
                )
        );
        frameInit();
    }

    /**
     * 窗体布局初始化
     */
    private void frameInit() {
        //设置Frame的大小
        this.setSize(600, 380);
        //设置窗口显示在桌面默认位置
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        int x = (int) (toolkit.getScreenSize().getWidth() - this.getWidth()) / 2;
        int y = (int) (toolkit.getScreenSize().getHeight() - this.getHeight()) / 2;
        this.setLocation(x, y);
        //设置Frame的背景色
//        this.setBackground(Color.blue);
        //设置表格布局
//        this.setLayout(new GridLayout(3,2));
        //为了关闭窗口
        this.addWindowListener(new WindowAdapter() {
            public void
            windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        //设置窗口图标
        try {
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            InputStream icoStream = classLoader.getResourceAsStream("images/logo.png");
            if (icoStream != null) {
                Image icon = ImageIO.read(icoStream);
                if (icon != null) {
                    this.setIconImage(icon);
                }
            }
        } catch (Exception ignored) {

        }

        Panel pannel = new Panel(new GridLayout(6, 2));

        int defaultInputColumns = 30;
        String defaultStr = "  ";

        // Res = Zmax - Re
        JLabel label_res = new JLabel(defaultStr + "* Res(电气系统的等值电阻值，Zmax-Re)：Ω");
        pannel.add(label_res);
        JTextField textField_res = new JTextField(defaultInputColumns);
        pannel.add(textField_res);

        //直接填写Res就不用填写Zmax和Re了
        // Zmax
        JLabel label_zmax = new JLabel(defaultStr + "* Zmax(阻抗峰的电阻)：Ω");
//        pannel.add(label_zmax);
        JTextField textField_zmax = new JTextField(defaultInputColumns);
//        pannel.add(textField_zmax);

        // Re
        JLabel label_re = new JLabel(defaultStr + "* Re(音圈的直流电阻)：Ω");
//        pannel.add(label_re);
        JTextField textField_re = new JTextField(defaultInputColumns);
//        pannel.add(textField_re);

        // Mms
        JLabel label_mms = new JLabel(defaultStr + "* Mms(振动质量)：克");
        pannel.add(label_mms);
        JTextField textField_mms = new JTextField(defaultInputColumns);
        pannel.add(textField_mms);

        // Cms
        JLabel label_cms = new JLabel(defaultStr + "* Cms(力顺)：mm/N");
        pannel.add(label_cms);
        JTextField textField_cms = new JTextField(defaultInputColumns);
        pannel.add(textField_cms);

        // BL
        JLabel label_bl = new JLabel(defaultStr + "* BL(磁力)：Tm");
        pannel.add(label_bl);
        JTextField textField_bl = new JTextField(defaultInputColumns);
        pannel.add(textField_bl);

        // Qms
        JLabel label_qmsOld = new JLabel(defaultStr + "Qms(其他软件计算的值，用于对比，可不填)");
        pannel.add(label_qmsOld);
        JTextField textField_qmsOld = new JTextField(defaultInputColumns);
        pannel.add(textField_qmsOld);

        //运算
        JButton button_reset = new JButton("Reset(重置)");
        JButton button_ok = new JButton("Calculate(计算)");
        Panel pannel_btn = new Panel(new GridLayout(1, 2));
        pannel_btn.add(button_reset);
        pannel_btn.add(button_ok);
        pannel.add(pannel_btn);
        JLabel label_result = new JLabel("    ---");
        pannel.add(label_result);

        //充值按钮添加事件
        button_reset.addActionListener(
                new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        textField_res.setText("");
                        textField_zmax.setText("");
                        textField_re.setText("");
                        textField_mms.setText("");
                        textField_cms.setText("");
                        textField_bl.setText("");
                        textField_qmsOld.setText("");
                        label_result.setText("    ---");
                    }
                }

        );

        //计算按钮添加事件
        button_ok.addActionListener(
                new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        QmsCalculateParam param = getInputValues(
                                textField_res,
                                textField_zmax,
                                textField_re,
                                textField_mms,
                                textField_cms,
                                textField_bl,
                                textField_qmsOld
                        );
                        if (param != null) {
                            Double qms = param.getQms();
                            if (qms != null && qms > 0) {
                                if (param.getDeviationPercentage() != null && param.getDeviationPercentage().compareTo(BigDecimal.ZERO) > 0) {
                                    label_result.setText(String.format("    Qms = %s，偏差率%s%%", qms.toString(), param.getDeviationPercentage()));
                                } else {
                                    label_result.setText("    Qms = " + qms.toString());
                                }
                            } else {
                                label_result.setText("    ---");
                            }
                        } else {
                            label_result.setText("    ---");
                        }
                    }
                });

        this.add(pannel);
        //java函数！自动整合更美观
        this.pack();
    }

    /**
     * 检查参数输入，并返回参数对象
     *
     * @return
     */
    private QmsCalculateParam getInputValues(
            JTextField textField_res,
            JTextField textField_zmax,
            JTextField textField_re,
            JTextField textField_mms,
            JTextField textField_cms,
            JTextField textField_bl,
            JTextField textField_qms
    ) {
        QmsCalculateParam param = new QmsCalculateParam();

        String res = textField_res.getText();
        String zmax = textField_zmax.getText();
        String re = textField_re.getText();
        String mms = textField_mms.getText();
        String cms = textField_cms.getText();
        String bl = textField_bl.getText();
        String qmsOld = textField_qms.getText();

        if (StringUtil.isEmpty(res)) {
            JOptionPane.showMessageDialog(null, "请填写Res的值，单位：欧姆", "提示", JOptionPane.WARNING_MESSAGE);
            return null;
        }
        res = res.replaceAll(" ", "");
        if (!StringUtil.isNumeric(res)) {
            JOptionPane.showMessageDialog(null, "Res的值不正确", "提示", JOptionPane.WARNING_MESSAGE);
            return null;
        }
        param.setRes(Double.valueOf(res));

//        if (StringUtil.isEmpty(zmax)) {
//            JOptionPane.showMessageDialog(null, "请填写Zmax的值，单位：欧姆", "提示", JOptionPane.WARNING_MESSAGE);
//            return null;
//        }
//        zmax = zmax.replaceAll(" ", "");
//        if (!StringUtil.isNumeric(zmax)) {
//            JOptionPane.showMessageDialog(null, "Zmax的值不正确", "提示", JOptionPane.WARNING_MESSAGE);
//            return null;
//        }
//        param.setZmax(Double.valueOf(zmax));
//
//        if (StringUtil.isEmpty(re)) {
//            JOptionPane.showMessageDialog(null, "请填写Re的值，单位：欧姆", "提示", JOptionPane.WARNING_MESSAGE);
//            return null;
//        }
//        re = re.replaceAll(" ", "");
//        if (!StringUtil.isNumeric(re)) {
//            JOptionPane.showMessageDialog(null, "re的值不正确", "提示", JOptionPane.WARNING_MESSAGE);
//            return null;
//        }
//        param.setRe(Double.valueOf(re));

        if (StringUtil.isEmpty(mms)) {
            JOptionPane.showMessageDialog(null, "请填写Mms的值，单位：克", "提示", JOptionPane.WARNING_MESSAGE);
            return null;
        }
        mms = mms.replaceAll(" ", "");
        if (!StringUtil.isNumeric(mms)) {
            JOptionPane.showMessageDialog(null, "Mms的值不正确", "提示", JOptionPane.WARNING_MESSAGE);
            return null;
        }
        param.setMms(Double.valueOf(mms));

        if (StringUtil.isEmpty(cms)) {
            JOptionPane.showMessageDialog(null, "请填写Cms的值，单位：欧姆", "提示", JOptionPane.WARNING_MESSAGE);
            return null;
        }
        cms = cms.replaceAll(" ", "");
        if (!StringUtil.isNumeric(cms)) {
            JOptionPane.showMessageDialog(null, "Cms的值不正确", "提示", JOptionPane.WARNING_MESSAGE);
            return null;
        }
        param.setCms(Double.valueOf(cms));

        if (StringUtil.isEmpty(bl)) {
            JOptionPane.showMessageDialog(null, "请填写BL的值，单位：欧姆", "提示", JOptionPane.WARNING_MESSAGE);
            return null;
        }
        bl = bl.replaceAll(" ", "");
        if (!StringUtil.isNumeric(bl)) {
            JOptionPane.showMessageDialog(null, "BL的值不正确", "提示", JOptionPane.WARNING_MESSAGE);
            return null;
        }
        Double blDouble = Double.valueOf(bl);
        if (blDouble <= 0) {
            JOptionPane.showMessageDialog(null, "BL的值不能小于等于零", "提示", JOptionPane.WARNING_MESSAGE);
            return null;
        }
        param.setBl(blDouble);

        if (!StringUtil.isEmpty(qmsOld)) {
            qmsOld = qmsOld.replaceAll(" ", "");
            if (!StringUtil.isNumeric(qmsOld)) {
                JOptionPane.showMessageDialog(null, "用于对比的Qms的值不正确", "提示", JOptionPane.WARNING_MESSAGE);
                return null;
            }
            Double qmsOldDouble = Double.valueOf(qmsOld);
            param.setQmsOld(qmsOldDouble);
        }

        return param;
    }

}
